<template>
  <div class="container">
    <div class="header">
      <h1>精品课程管理</h1>
      <div class="actions">
        <el-button type="primary" @click="addCourse">添加课程</el-button>
      </div>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="课程名称">
          <el-input v-model="searchForm.lessonName" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item label="教师">
          <el-select v-model="searchForm.teacherId" placeholder="请选择教师" style="width: auto" clearable>
            <el-option
              v-for="item in teacherOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="courseList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" prop="id" label="ID" width="80" />
        <el-table-column label="课程图片" width="120">
          <template #default="scope">
            <div class="image-preview">
              <img
                style="width: 80px; height: 50px; object-fit: cover; border-radius: 4px;"
                :src="scope.row.leassonPictureUrl || 'https://placeholder.pics/svg/200x120'"
              />
              <div class="image-actions">
                <el-button
                  type="primary"
                  size="small"
                  circle
                  @click="previewImage(scope.row.leassonPictureUrl)"
                  :disabled="!scope.row.leassonPictureUrl">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
                <el-button
                  v-if="scope.row.id"
                  type="primary"
                  size="small"
                  circle
                  @click="showImageUploadDialog(scope.row)"
                  :disabled="scope.row.deleteFlag === 1">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lessonName" label="课程标题" />
        <el-table-column prop="teacherName" label="教师" />
        <el-table-column label="跳转链接" width="300">
          <template #default="scope">
            <div class="link-edit">
              <el-input
                v-if="scope.row.isEditingLink"
                v-model="scope.row.tempJumpUrl"
                size="small"
                @blur="saveJumpUrl(scope.row)"
                @keyup.enter="saveJumpUrl(scope.row)"
              />
              <div v-else class="link-display">
                <span class="link-text" :title="scope.row.jumpUrl">{{ scope.row.jumpUrl }}</span>
                <el-button
                  type="primary"
                  size="small"
                  link
                  :disabled="scope.row.deleteFlag === 1"
                  @click="editJumpUrl(scope.row)"
                >
                  编辑
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lessonDescription" label="课程描述" show-overflow-tooltip />
        <el-table-column label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.deleteFlag === 0 ? 'success' : 'danger'">
              {{ scope.row.deleteFlag === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="editCourse(scope.row)" :disabled="scope.row.deleteFlag === 1">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="confirmDelete(scope.row)"
              :disabled="scope.row.deleteFlag === 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片上传对话框 -->
    <el-dialog title="上传课程图片" v-model="imageDialogVisible" width="400px">
      <div class="upload-container">
        <el-upload
          class="image-uploader"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleImageChange"
          accept="image/jpeg,image/png,image/gif"
        >
          <el-image 
            v-if="imagePreview" 
            :src="imagePreview" 
            class="uploaded-image"
            fit="cover" />
          <el-icon v-else class="image-uploader-icon"><plus /></el-icon>
        </el-upload>
        <div class="upload-tip">请上传课程图片，建议比例 16:9</div>
        <div v-if="imagePreview" class="preview-actions">
          <el-button type="primary" @click="previewImage(imagePreview)">
            <el-icon><ZoomIn /></el-icon> 预览大图
          </el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="imageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadCourseImage" :loading="uploading" :disabled="!imageFile">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px" append-to-body center>
      <div class="image-preview-dialog">
        <el-image
          style="width: 100%;"
          :src="previewImageUrl"
          fit="contain"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ZoomIn, Edit } from '@element-plus/icons-vue'
import { pageLessons, deleteLesson, updateLesson } from '@/api/lesson'
import { uploadFile } from '@/api/upload'
import { getTeacherSelectList } from '@/api/teacher'

const router = useRouter()
const loading = ref(false)
const courseList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const teacherOptions = ref([])

const searchForm = reactive({
  lessonName: '',
  teacherId: null
})

// 图片上传相关变量
const imageDialogVisible = ref(false)
const imageFile = ref(null)
const imagePreview = ref('')
const currentCourse = ref(null)
const uploading = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-';
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取教师列表
const fetchTeachers = async () => {
  try {
    const res = await getTeacherSelectList()
    if (res && res.code === 200 && res.data) {
      teacherOptions.value = res.data.map(item => ({
        value: item.id,
        label: item.teacherName
      }))
    }
  } catch (error) {
    console.error('获取教师列表失败', error)
  }
}

// 添加课程
const addCourse = () => {
  router.push('/course/add')
}

// 编辑课程
const editCourse = (row) => {
  router.push(`/course/edit/${row.id}`)
}

// 确认删除
const confirmDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除课程"${row.lessonName}"吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    handleDelete(row.id)
  }).catch(() => {})
}

// 处理删除
const handleDelete = async (id) => {
  try {
    loading.value = true
    await deleteLesson(id)
    ElMessage.success('删除成功')
    fetchData() // 重新加载数据
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.lessonName = ''
  searchForm.teacherId = null
  currentPage.value = 1
  fetchData()
}

// 编辑跳转链接
const editJumpUrl = (row) => {
  row.isEditingLink = true
  row.tempJumpUrl = row.jumpUrl
}

// 保存跳转链接
const saveJumpUrl = async (row) => {
  if (row.tempJumpUrl !== row.jumpUrl) {
    try {
      loading.value = true
      const updatedLesson = {
        id: row.id,
        jumpUrl: row.tempJumpUrl
      }
      await updateLesson(updatedLesson)
      row.jumpUrl = row.tempJumpUrl
      ElMessage.success('跳转链接更新成功')
    } catch (error) {
      console.error('更新跳转链接失败', error)
      ElMessage.error('更新跳转链接失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  row.isEditingLink = false
}

// 显示图片上传对话框
const showImageUploadDialog = (course) => {
  currentCourse.value = course
  imagePreview.value = course.leassonPictureUrl || ''
  imageFile.value = null
  imageDialogVisible.value = true
}

// 处理图片选择，只是本地预览，不上传
const handleImageChange = (file) => {
  imageFile.value = file.raw
  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(imageFile.value)
}

// 上传课程图片，点击按钮后才上传
const uploadCourseImage = async () => {
  if (!imageFile.value || !currentCourse.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  try {
    uploading.value = true
    const res = await uploadFile(imageFile.value, 'course')

    if (res && res.code === 200) {
      // 更新课程信息
      const updatedLesson = {
        id: currentCourse.value.id,
        leassonPictureUrl: `http://localhost:8080/api`+res.message
      }

      await updateLesson(updatedLesson)
      ElMessage.success('课程图片上传成功')
      imageDialogVisible.value = false

      // 重新加载数据以显示最新图片
      fetchData()
    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传课程图片失败', error)
    ElMessage.error('上传课程图片失败：' + (error.message || '未知错误'))
  } finally {
    uploading.value = false
  }
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      lessonName: searchForm.lessonName || undefined,
      teacherId: searchForm.teacherId || undefined
    }

    const res = await pageLessons(params)
    if (res && res.code === 200 && res.data) {
      // 为每一行添加编辑状态属性
      const records = res.data.records || []
      records.forEach(record => {
        record.isEditingLink = false
        record.tempJumpUrl = record.jumpUrl
      })
      courseList.value = records
      total.value = res.data.total || 0
    } else {
      throw new Error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取课程数据失败', error)
    ElMessage.error('获取课程数据失败：' + (error.message || '未知错误'))
    courseList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

onMounted(() => {
  fetchTeachers()
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      font-size: 24px;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .link-edit {
    width: 100%;
  }

  .link-display {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .link-text {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .image-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
    
    .image-actions {
      display: flex;
      gap: 5px;
    }
  }

  .upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .preview-actions {
      margin-top: 10px;
    }
  }

  .image-preview-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
}
</style>
